package com.hzy.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzy.common.core.page.TableDataInfo;
import com.hzy.common.exception.base.BaseException;
import com.hzy.common.utils.UserThreadLocal;
import com.hzy.nursing.dto.ReservationDto;
import com.hzy.nursing.vo.TimeCountVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hzy.nursing.mapper.ReservationMapper;
import com.hzy.nursing.domain.Reservation;
import com.hzy.nursing.service.IReservationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;

/**
 * 预约信息Service业务层处理
 *
 * @author HZY
 * @date 2025-10-11
 */
@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements IReservationService {
    @Autowired
    private ReservationMapper reservationMapper;


    @Override
    public List<TimeCountVo> countReservationsForTime(Long time) {
        LocalDateTime localDateTime = LocalDateTimeUtil.of(time);
        LocalDateTime startOfDay = localDateTime.toLocalDate().atStartOfDay();
        LocalDateTime endOfDay = startOfDay.plusDays(1);
        List<TimeCountVo> timeCountVoList = reservationMapper.countReservationsForTime(startOfDay, endOfDay);
        return timeCountVoList;
    }

    @Override
    public int getCancelledCount(Long userId) {
        LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
        LocalDateTime endOfDay = startOfDay.plusDays(1);
        LambdaQueryWrapper<Reservation> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Reservation::getCreateBy, userId);
        lambdaQueryWrapper.eq(Reservation::getStatus, 2);
        lambdaQueryWrapper.between(Reservation::getUpdateTime, startOfDay, endOfDay);
        return (int) count(lambdaQueryWrapper);
    }

    @Override
    public long countByReservationTime(LocalDateTime reservationTime) {
        LambdaQueryWrapper<Reservation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Reservation::getTime, reservationTime);
        wrapper.ne(Reservation::getStatus, 2);
        return count(wrapper);
    }

    @Override
    public TableDataInfo findByPage(int pageNum, int pageSize, Integer status) {
        Long userId = UserThreadLocal.getUserId();
        if (ObjectUtil.isEmpty(userId)) {
            throw new BaseException("请先登录");
        }
        LambdaQueryWrapper<Reservation> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Reservation::getCreateBy, userId);
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(status), Reservation::getStatus, status);
        lambdaQueryWrapper.orderByDesc(Reservation::getCreateTime);
        Page<Reservation> page = new Page<>(pageNum, pageSize);
        page = page(page, lambdaQueryWrapper);
        return createTableDataInfo(page);
    }


    private TableDataInfo createTableDataInfo(Page<Reservation> page) {
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setMsg("请求成功");
        tableDataInfo.setCode(200);
        return tableDataInfo;
    }

    @Override
    public int cancelReservation(Long id) {
        Long userId = UserThreadLocal.getUserId();
        Reservation reservation = getById(id);
        if (ObjectUtil.isEmpty(reservation)) {
            throw new BaseException("预约不存在");
        }
        // 安全校验：确保用户只能取消自己的预约
        if (!reservation.getCreateBy().equals(userId)) {
            throw new BaseException("无权操作他人预约");
        }
        reservation.setStatus(2); // 2: 取消
        reservation.setUpdateBy(String.valueOf(userId));
        reservation.setUpdateTime(LocalDateTime.now());
        return updateById(reservation) ? 1 : 0;
    }

    @Override
    public Reservation selectReservationById(Long id) {
        return getById(id);
    }

    @Override
    public List<Reservation> selectReservationList(Reservation reservation) {
        return reservationMapper.selectReservationList(reservation);
    }

    @Override
    public int insertReservation(ReservationDto reservationDto) {
        Long userId = UserThreadLocal.getUserId();
        Reservation reservation = BeanUtil.toBean(reservationDto, Reservation.class);
        reservation.setCreateBy(String.valueOf(userId));
        reservation.setUpdateBy(String.valueOf(userId));
        reservation.setCreateTime(LocalDateTime.now());
        reservation.setUpdateTime(LocalDateTime.now());
        reservation.setStatus(0);
        return save(reservation) ? 1 : 0;
    }

    @Override
    public int updateReservation(Reservation reservation) {
        return updateById(reservation) ? 1 : 0;
    }

    @Override
    public int deleteReservationByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    @Override
    public int deleteReservationById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void updateReservationStatus() {
        LocalDateTime now = LocalDateTime.now();
        LambdaQueryWrapper<Reservation> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Reservation::getStatus, 0);
        lambdaQueryWrapper.lt(Reservation::getTime, now);
        List<Reservation> list = list(lambdaQueryWrapper);
        if (CollUtil.isNotEmpty(list)) {
            for (Reservation reservation : list) {
                reservation.setStatus(3);
                reservation.setUpdateTime(now);
            }
            updateBatchById(list);
        }
    }
}